import streamlit as st
import os
from pathlib import Path

st.set_page_config(page_title="文件批量重命名工具", layout="wide")
st.title("📁 文件批量重命名工具")


def _get_directories(current_path=""):
    """获取当前目录的子目录列表"""
    if not current_path or not os.path.isdir(current_path):
        current_path = os.path.expanduser("~")

    try:
        items = []
        # 添加上级目录
        parent_dir = os.path.dirname(current_path)
        if parent_dir != current_path:
            items.append(f"📁 .. ({parent_dir})")

        # 获取当前目录的子目录
        for item in sorted(os.listdir(current_path)):
            item_path = os.path.join(current_path, item)
            if os.path.isdir(item_path):
                items.append(f"📁 {item} ({item_path})")

        return items
    except PermissionError:
        return []


# 初始化session state
if "selected_dir" not in st.session_state:
    st.session_state.selected_dir = ""
if "selected_files" not in st.session_state:
    st.session_state.selected_files = {}
if "new_names" not in st.session_state:
    st.session_state.new_names = {}

# 侧边栏：目录选择
st.sidebar.header("设置")

# 初始化当前浏览路径
if "current_browse_path" not in st.session_state:
    st.session_state.current_browse_path = os.path.expanduser("~")

# 获取子目录选项
dir_options = _get_directories(st.session_state.current_browse_path)

# 显示当前路径
st.sidebar.text(f"📍 当前: {st.session_state.current_browse_path}")

selected_item = st.sidebar.selectbox(
    "📁 浏览目录:", options=dir_options, index=None, placeholder="选择一个目录..."
)

# 处理目录选择
if selected_item:
    # 提取路径（从括号中）
    path = selected_item.split("(")[-1].rstrip(")")

    if selected_item.startswith("📁 .."):
        # 返回上级目录
        st.session_state.current_browse_path = path
    else:
        # 进入子目录
        st.session_state.current_browse_path = path

    st.rerun()

# 确认选择当前目录作为工作目录
col1, col2 = st.sidebar.columns([1, 1])
with col1:
    if st.button("✅ 选择此目录", use_container_width=True):
        st.session_state.selected_dir = st.session_state.current_browse_path
        st.rerun()

with col2:
    if st.button("🏠 回到主目录", use_container_width=True):
        st.session_state.current_browse_path = os.path.expanduser("~")
        st.rerun()

folder_path = st.session_state.selected_dir

if folder_path and os.path.isdir(folder_path):
    st.session_state.selected_dir = folder_path

    # 获取目录中的所有文件
    files = [
        f
        for f in os.listdir(folder_path)
        if os.path.isfile(os.path.join(folder_path, f))
    ]
    files.sort()

    if files:
        st.sidebar.success(f"✅ 找到 {len(files)} 个文件")

        # 主区域：文件选择和重命名
        st.subheader("文件列表")

        col1, col2, col3 = st.columns([1, 3, 3])
        with col1:
            st.write("**选择**")
        with col2:
            st.write("**原文件名**")
        with col3:
            st.write("**新文件名**")

        st.divider()

        # 显示文件列表
        for idx, filename in enumerate(files):
            col1, col2, col3 = st.columns([1, 3, 3])

            with col1:
                # 选择框
                is_selected = st.checkbox(
                    "选择",
                    value=st.session_state.selected_files.get(filename, False),
                    key=f"checkbox_{filename}",
                )
                st.session_state.selected_files[filename] = is_selected

            with col2:
                st.text(filename)

            with col3:
                if is_selected:
                    # 获取文件扩展名
                    file_ext = Path(filename).suffix
                    base_name = Path(filename).stem

                    new_name = st.text_input(
                        "新名称",
                        value=st.session_state.new_names.get(
                            filename, f"{base_name}({idx+1}){file_ext}"
                        ),
                        key=f"rename_{filename}",
                        label_visibility="collapsed",
                    )
                    st.session_state.new_names[filename] = new_name
                else:
                    st.session_state.new_names.pop(filename, None)

        st.divider()

        # 获取选中的文件
        selected_files_list = [
            f for f, selected in st.session_state.selected_files.items() if selected
        ]

        if selected_files_list:
            st.subheader(f"📋 预览 ({len(selected_files_list)} 个文件)")

            preview_data = []
            for filename in selected_files_list:
                old_path = os.path.join(folder_path, filename)
                new_name = st.session_state.new_names.get(filename, filename)
                new_path = os.path.join(folder_path, new_name)

                preview_data.append(
                    {
                        "原文件名": filename,
                        "新文件名": new_name,
                        "状态": (
                            "✅ 可以重命名" if filename != new_name else "⚠️ 名称未改变"
                        ),
                    }
                )

            st.dataframe(preview_data, use_container_width=True)

            # 执行重命名
            col1, col2, col3 = st.columns([2, 1, 1])

            with col2:
                if st.button("🔄 执行重命名", type="primary", use_container_width=True):
                    success_count = 0
                    error_count = 0
                    errors = []

                    for filename in selected_files_list:
                        old_path = os.path.join(folder_path, filename)
                        new_name = st.session_state.new_names.get(filename, filename)
                        new_path = os.path.join(folder_path, new_name)

                        try:
                            if filename != new_name and not os.path.exists(new_path):
                                os.rename(old_path, new_path)
                                success_count += 1
                            elif os.path.exists(new_path):
                                errors.append(f"{new_name} - 文件已存在")
                                error_count += 1
                        except Exception as e:
                            errors.append(f"{filename} - {str(e)}")
                            error_count += 1

                    # 显示结果
                    if success_count > 0:
                        st.success(f"✅ 成功重命名 {success_count} 个文件")

                    if error_count > 0:
                        st.error(f"❌ 失败 {error_count} 个文件")
                        for error in errors:
                            st.write(f"  • {error}")

                    # 清空状态，刷新
                    st.session_state.selected_files = {}
                    st.session_state.new_names = {}

            with col3:
                if st.button("🗑️ 清空选择", use_container_width=True):
                    st.session_state.selected_files = {}
                    st.session_state.new_names = {}
                    st.rerun()

        else:
            st.info("👈 选择左侧的文件框来编辑文件名")

    else:
        st.warning("此目录中没有文件")

elif folder_path and not os.path.isdir(folder_path):
    st.error("❌ 路径不存在或不是目录")

else:
    st.info("👈 在左侧浏览目录并点击「选择此目录」开始")
